package net.cz.wc.command;

import java.sql.Connection;
import java.sql.ResultSet;

import net.cz.wc.dao.SingleMetricConnectedDAO;
import net.cz.wc.data.ConnectionManager;
import net.cz.wc.main.Context;
import net.cz.wc.output.ConsoleOutput;
import net.cz.wc.output.QueryOutput;

/**
 * Command implementation for data extraction
 * 
 * @author carloszuluaga
 *
 */
public class ExtractCommand implements Command {
	
	/**
	 * Validates if input arguments are valid
	 * @param args
	 * @return true if arguments are valid or false if they don't
	 */
	private boolean validArgs(String[] args) {
		return true;
	}
	
	/**
	 * Executes the extract data command by parsing input arguments and executing
	 * a query into the database
	 */
	public void execute(String[] args) {
		Context.getContext().addDebugMessage("ExtractCommand.execute()");
		
		if (!validArgs(args)) {
			Context.getContext().addErrorMessage("invalid args for ext command");
			return;
		}
		
		for (int i = 0; i < args.length; i++) {
			System.out.println("arg " + i + " - " + args[i]);
		}
		Connection conn = null;
		
		ConsoleOutput.printDefaultHeader();
		
		try {
			conn = ConnectionManager.getConnection();
			conn.setAutoCommit(false);
			SingleMetricConnectedDAO dao = new SingleMetricConnectedDAO(conn);
			
			prepareMetricDao(args, dao);
			
			long resultSize = 0;
			
			ResultSet rst = dao.getSingleMetrics();
			while (rst.next()) {
				resultSize++;
				QueryOutput output = new QueryOutput();
				output.setLogId(rst.getLong(1));
				output.setMetricTime(rst.getTimestamp(2));
				output.setMetricName(rst.getString(3));
				output.setMetricValue(rst.getLong(4));
				
				ConsoleOutput.printDefault(output);
			}
			
			dao.closeDAO();
			
			if (resultSize != 1) {
				Context.getContext().addSuccessMessage(resultSize + " metrics printed");
			} else {
				Context.getContext().addSuccessMessage(resultSize + " metric printed");
			}
		} catch (Exception ee) {
			Context.getContext().printException(ee);
		} finally {
			ConnectionManager.closeConnection(conn);
		}
	}
	
	/**
	 * Prepares the dao to execute the query with all of the parameter
	 * given by the input arguments
	 * @param args input arguments
	 * @param dao object to set the filter
	 */
	private void prepareMetricDao(String[] args, SingleMetricConnectedDAO dao) {
		if (args.length == 1) {
			return;
		}
		
		for (int i = 1; i < args.length; i++) {
			if ("-m".equals(args[i])) {
				dao.addFilterExpresion("metric_name", "~*", ".*:" + args[i + 1]);
			} else if ("-log".equals(args[i])) {
				dao.addFilterExpresion("id_log", "=", args[i + 1]);
			} else if ("-exp".equals(args[i])) {
				dao.addFilterExpresion("metric_name", "~*", args[i + 1]);
			}
		}
	}
}
